/**
 * 快速检索
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, Collapse, Input, Select, message, DatePicker, Spin } from 'antd';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';

import {
  listUnderchargeLuggageQuick,
  listUnderchargeLuggage,
  selectCityInfo,
  listUnderchargeLuggageQuickCount
} from './service.js';
import { Const } from './Const';

import AuthComponent from '@/components/Authorized/AuthComponent';
import Detail from './components/Detail';

const { Panel } = Collapse;
const { Option } = Select;

class PrivateData {
  static isFirst = true;
  // 事故单类型 1破损行李 2少收行李 3多收行李 4异常行李 5赔偿箱包 6内物缺失 7出港破损
  static typeMap = {
    // 1: '进港少收',
    // 2: '进港破损',
    // 3: '进港内物缺失',
    // 4: '进港多收',
    1: '进港破损',
    2: '进港少收',
    3: '进港多收',
    6: '进港内物缺失',
    7: '出港破损',
  };
  // 事故单类型 1破损行李 2少收行李 3多收行李 4异常行李
  static iconList = [
    { text: '少收', icon: require('./images/1.png'), value: 'underchargeCount', arr: [2] },
    { text: '内物丢失', icon: require('./images/2.png'), value: 'lostCount', arr: [6] },
    { text: '破损', icon: require('./images/3.png'), value: 'breakCount', arr: [1, 7] },
    { text: '总赔偿金额', icon: require('./images/4.png'), value: 'totalPayMoney', arr: [0] },
  ];
  static addBtnList = [
    { name: '添加进港破损事故单', type: 1, authCode: 'damagedLuggage.basicPermissions' },
    { name: '添加进港少收事故单', type: 2, authCode: 'lessLuggage.basicPermissions' },
    { name: '添加进港多收事故单', type: 3, authCode: 'moreLuggage.basicPermissions' },
    { name: '添加进港内物缺失事故单', type: 6, authCode: 'internalMissingLuggage.basicPermissions' },
  ]
}

const QuickRetrieval = props => {

  const { location: { state } } = props;

  const actionRef = useRef();
  const ref = useRef();

  const actionRefLess = useRef();
  const refLess = useRef();

  const [height, controlH] = useState(300); // table高度
  const [isCollapse, controlC] = useState(true);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 勾选索引
  const [selectedRows, setSelectedRows] = useState([]); // 勾选列

  const [selectedLessRowKeys, setSelectedLessRowKeys] = useState([]); // 勾选少收信息索引
  const [selectedLessRows, setSelectedLessRows] = useState([]); // 勾选少收信息列

  const [detailVisible, setDetailVisible] = useState(false);
  const [detailTitle, setDetailTitle] = useState('');

  const [iconData, setIconData] = useState({}); // 统计信息

  const [searchDataParams, setSearchDataParams] = useState({}); // 搜索信息

  const [createStartTime, setCreateStartTime] = useState(''); // 开始时间
  const [createEndTime, setCreateEndTime] = useState(''); // 结束时间

  const [detailType, setDetailType] = useState('');

  // 航站下拉列表
  const { data: selectCityData = [] } = useRequest(selectCityInfo);

  // 获取四个数量
  const { run: runListUnderchargeLuggageQuickCount, loading: countLoading } = useRequest(params => listUnderchargeLuggageQuickCount(params), {
    manual: true,
    onSuccess (res) {
      let data = res || {};
      let _iconData = {};
      for (let item of PrivateData.iconList) {
        _iconData[item.value] = data[item.value] || 0;
      }
      setIconData(_iconData);
    }
  })

  useEffect(() => {
    return () => {
      PrivateData.isFirst = true;
    };
  }, []);

  useEffect(() => {
    if (PrivateData.isFirst) {
      let obj = {};
      let searchData = state?.searchData || {};
      let num = 0;
      for (let key in searchData) {
        if (!searchData[key]) continue;
        if (key === 'flightDate' || key === 'startTime' || key === 'endTime') {
          obj[key] = moment(searchData[key]);
          num++;
          continue;
        }
        num++;
        obj[key] = searchData[key];
      }

      if (num >= 1) {
        setTimeout(() => {
          ref.current.setFieldsValue({
            ...obj
          })
        }, 0);
      }

    }

  }, [state]);

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 370);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isCollapse]);

  const disabledStartDate = useCallback((current) => {
    if (createEndTime) return current && (current > moment().endOf('day') || current > moment(createEndTime).endOf('day'));
    return current && current > moment().endOf('day');
  }, [createEndTime]);

  const disabledEndDate = useCallback((current) => {
    if (createStartTime) return current && (current > moment().endOf('day') || current < moment(createStartTime).startOf('day'));
    return current && current > moment().endOf('day');
  }, [createStartTime]);

  // 添加事故单
  const goToAddEditIncident = useCallback((selectedRows) => {
    if (selectedRows.length !== 1) return;
    if (state?.ownerType === 3) {
      let lessInfoListId = selectedLessRowKeys && selectedLessRowKeys.length >= 1 ? selectedLessRowKeys[0]: '';
      router.push({
        pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncidentMore',
        state: {
          type: 'add',
          ownerType: state?.ownerType,
          itemData: selectedRows[0],
          isHave: selectedRows.length === 0 ? false : true,
          lessInfoListId
        }
      });
    } else {
      router.push({
        pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncident',
        state: {
          type: 'add',
          ownerType: state?.ownerType,
          itemData: selectedRows,
          isHave: selectedRows.length === 0 ? false : true
        }
      });
    }
  }, [state, selectedLessRowKeys]);

  const goToAddEditIncidentSingle = useCallback((selectedRows, type) => {
    if (selectedRows.length !== 1) return;
    if (type === 3) {
      router.push({
        pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncidentMore',
        state: {
          type: 'add',
          ownerType: type,
          itemData: selectedRows[0],
          isHave: selectedRows.length === 0 ? false : true,
          lessInfoListId: '',
          isFromQuickRetrieval: '1'
        }
      });
    } else {
      router.push({
        pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncident',
        state: {
          type: 'add',
          ownerType: type,
          itemData: selectedRows,
          isHave: selectedRows.length === 0 ? false : true,
          isFromQuickRetrieval: '1'
        }
      });
    }
  }, [state]);

  // 打开详情弹窗
  const openDetail = useCallback((item, index) => {
    if (index === 3) return;
    if (+iconData[item.value] === 0) {
      message.warning('暂无数据');
      return;
    };
    setDetailType(item.arr.join(','));
    setDetailVisible(true);
    setDetailTitle(item.text);
  }, [state, iconData]);
  // 关闭详情弹窗
  const closeDetail = useCallback(() => {
    setDetailVisible(false);
    // setDetailTitle('');
  }, []);

  // rowSelection
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    if (selectedRows.length === 1) {
      if (state?.ownerType === 3) {
        setSelectedLessRowKeys([]);
        setSelectedLessRows([]);
        actionRefLess.current.reload();
      } else {
        let obj = {...selectedRows[0]};
        runListUnderchargeLuggageQuickCount({
          flightNo: obj.flightNo || '',
          idNo: obj.idNo || '',
          tktNo: obj.tktNo || '',
        });
      }
    }
    setSelectedRowKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  };
  const rowSelection = {
    type: 'radio',
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  const tableLessSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedLessRowKeys(selectedRowKeys);
    setSelectedLessRows(selectedRows);
  };
  const lessRowSelection = {
    type: 'radio',
    selectedLessRowKeys,
    onChange: tableLessSelectChange,
  };

  const columns = [
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 100,
      renderFormItem: (_, { onChange, value }) => {
        return <Input
          value={value}
          onChange= {e => {
            let value = Const.formatFlightNo(e.target.value);
            onChange(value);
          }}
          maxLength={6}
          placeholder="3U" />;
      }
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 100,
      valueType: 'date'
    },
    {
      title: '旅客航程',
      dataIndex: 'segment',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '证件类型',
      dataIndex: 'idType',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          placeholder="请选择"
          value={value}
          onChange={onChange}
        >
          {Const.idTypeListForSearch.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
        </Select>
      ),
    },
    {
      title: '证件号',
      dataIndex: 'idNo',
      width: 100,
      formItemProps: {
        maxLength: 18
      }
    },
    {
      title: '始发地',
      dataIndex: 'orgPlace',
      width: 100,
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '目的地',
      dataIndex: 'dstPlace',
      width: 100,
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      width: 100,
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={val => {
              setCreateStartTime(val);
              onChange(val);
            }}
            disabledDate={disabledStartDate}
            value={value}
          />
        );
      }
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      width: 100,
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={val => {
              setCreateEndTime(val);
              onChange(val);
            }}
            disabledDate={disabledEndDate}
            value={value}
          />
        );
      }
    },
    {
      title: '客票号',
      dataIndex: 'tktNo',
      width: 100,
      formItemProps: {
        maxLength: 13
      }
    },
    {
      title: '行李号',
      dataIndex: 'pkgNo',
      width: 100,
      formItemProps: {
        maxLength: 50
      }
    },
    {
      title: '行李总件数',
      dataIndex: 'pkgCount',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '行李总重量',
      dataIndex: 'pkgWeight',
      width: 100,
      hideInSearch: true,
    },
  ];

  const lessColumns = [
    {
      title: '事故单编号',
      dataIndex: 'accidentId',
      width: 200,
      fixed: 'left',
      hideInSearch: true,
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '证件类型',
      dataIndex: 'idType',
      width: 100,
      render: (text, record) => <span>{Const.idTypeMap[text]?.text || '-'}</span>,
      hideInSearch: true,
    },
    {
      title: '证件号',
      dataIndex: 'idNo',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '客票号',
      dataIndex: 'tktNo',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '旅客航程',
      dataIndex: 'voyage',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '行李号',
      dataIndex: 'pkgNo',
      width: 100,
      hideInSearch: true,
    },
  ];

  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        className={styles.compactTable}
        rowKey="id"
        rowSelection={rowSelection}
        toolBarRender={false}
        headerTitle={false}
        onSubmit={() => {
          setSelectedRowKeys([]);
          setSelectedRows([]);
          if (actionRefLess.current) actionRefLess.current.reload();
        }}
        request={params => {
          let searchData = state?.searchData || {};
          if (PrivateData.isFirst) {
            for (let key in searchData) {
              if (!searchData[key]) continue;
              params[key] = searchData[key];
            }
            PrivateData.isFirst = false;
          } else {
            if (!params.tktNo && !params.pkgNo && !params.idNo) {
              message.warning('客票号、行李牌号、证件号必填一项，请补充查询条件');
              return;
            }
            if (params.flightDate && (params.startTime || params.endTime)) {
              message.warning('航班日期、开始时间、结束时间不能同时存在');
              return;
            }
            if ((params.startTime && !params.endTime) || (!params.startTime && params.endTime)) {
              message.warning('开始时间和结束时间必须同时选择');
              return;
            }
            if (params.startTime && params.startTime.isValid()) {
              params.startTime = moment(params.startTime).format(Const.format);
            }
            if (params.endTime && params.endTime.isValid()) {
              params.endTime = moment(params.endTime).format(Const.format);
            }
          }

          setSearchDataParams(params);
          return listUnderchargeLuggageQuick(params);
        }}
        tableAlertRender={false}
        columns={columns}
        options={false}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
        }}
        scroll={{ x: 900, y: height }}
        search={{
          onCollapse: val => {
            controlC(val);
          },
          span: { // 设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
      >
      </ProTable>
      <Collapse activeKey={['1']} style={{ marginTop: '20px' }}>
        {(state?.ownerType !== 3 && selectedRows.length === 1) && <Panel showArrow={false} header="客户历史事故单记录" key="1">
          {countLoading ? <div className={styles['iconDataFCC']}>
            <Spin />
          </div> : <div className={styles.iconBox}>
            {PrivateData.iconList.map((item, index) => (
              <div className={`${styles.iconItem} ${index === 3 ? styles.cursorDefault : ''}`} key={index} onClick={() => openDetail(item, index)}>
                <div>
                  <img src={item.icon} />
                </div>
                <div>
                  <div>{item.text}</div>
                  <div>{iconData[item.value] || 0}</div>
                </div>
              </div>
            ))}
          </div>}
        </Panel>}
        {state?.ownerType === 3 && <Panel showArrow={false} header="对应少收信息" key="1">
          <ProTable
            className={styles.compactTable}
            actionRef={actionRefLess}
            formRef={refLess}
            rowKey="accidentId"
            rowSelection={lessRowSelection}
            toolBarRender={false}
            headerTitle={false}
            request={params => {

              if (selectedRows.length === 1) {
                let obj = selectedRows[0];
                let paramsArr = ['paxName', 'idNo', 'tktNo', 'flightNo', 'flightDate', 'pkgNo'];
                for (let item of paramsArr) {
                  params[item] = obj[item] || '';
                }
                params.status = '0,1,2'; // 过滤掉已作废的
              } else {
                return false;
              }

              return listUnderchargeLuggage(params);
            }}
            tableAlertRender={false}
            columns={lessColumns}
            options={false}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
            }}
            scroll={{ x: 900, y: height }}
            search={false}
          >
          </ProTable>
        </Panel>}
      </Collapse>
      <div className={styles.btnBox}>
        {state?.ownerType !== 0 && <Button
          type="primary"
          disabled={selectedRows.length !== 1}
          onClick={() => goToAddEditIncident(selectedRows)}>
          添加事故单
        </Button>}
        {state?.ownerType === 0 && <>
        {PrivateData.addBtnList.map((item, index) => {
          if (AuthComponent.getAuth(item.authCode)) {
            return <Button
              key={index}
              type="primary"
              style={{ marginRight: '10px' }}
              disabled={selectedRows.length !== 1}
              onClick={() => goToAddEditIncidentSingle(selectedRows, item.type)}>
              {item.name}
            </Button>
          }
        })}
        </>}
        <Button onClick={() => router.goBack()}>取消</Button>
      </div>
      <Detail
        modalVisible={detailVisible}
        onCancel={closeDetail}
        detailTitle={detailTitle}
        detailType={detailType}
        searchData={searchDataParams}>
      </Detail>
    </>
  )
};

export default QuickRetrieval;
